leetcode刷题记录22-23

介绍

Given two strings s and t which consist of only lowercase letters.

String t is generated by random shuffling string s and then add one more letter at a random position.

Find the letter that was added in t.

Example:

Input:
s = “abcd”
t = “abcde”

Output:
e

Explanation:
‘e’ is the letter that was added.

思路

暴力解决

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
slist=list(s)
slist.sort()
tlist=list(t)
tlist.sort()
find=False
for i in range(len(tlist)-1):
if tlist[i]!=slist[i]:
return tlist[i]
find=True
break
if not find:
return tlist[-1]

介绍

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Note:
You must not modify the array (assume the array is read only).
You must use only constant, O(1) extra space.
Your runtime complexity should be less than O(n2).
There is only one duplicate number in the array, but it could be repeated more than once.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

思路

既然多了个数变成n+1个数了,那按1到n对半分多的数肯定在多的那边,时间复杂度是O(nlogn)

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
m=len(nums)*0.5
l=0
r=len(nums)
find=False
while not find:
lcount=0
rcount=0
mcount=0
for i in nums:
if (i<m) and (i>l):
lcount=lcount+1
elif i==m:
mcount=mcount+1
if mcount>1:
return int(m)
find=True
break
elif (i>m) and (i<r):
rcount=rcount+1
else:
pass
if rcount<lcount:
if m-l<2:
for i in range(int(l),int(m)+2):
if find:
break
icount=0
for j in nums:
if i==j:
icount=icount+1
if icount>1:
return i
find=True
break
else:
r=m
m=(r+l)*0.5
else:
if r-m<2:
for i in range(int(m),int(r)+2):
if find:
break
icount=0
for j in nums:
if i==j:
icount=icount+1
if icount>1:
return i
find=True
break
else:
l=m
m=(r+l)*0.5